define(function (require) {
var zsApp = require('app');  
zsApp.controller('institutionCtrl', ['$rootScope', '$scope', '$http', '$timeout', 'cache', 'selectCache', 'promptCache', function($rootScope, $scope, $http, $timeout, cache, selectCache, promptCache) {
    
    // pagination
    $rootScope.paginationConf = { 
        currentPage    : 1,
        totalItems     : 10,
        itemsPerPage   : 10,
        pagesLength    : 15,
        perPageOptions : [20, 30, 40, 50, 60],
        onChange: function() { // console.log(cache.get('institutionId'));
            var self = this,
                treeReqVo = {
                    id          : cache.get('institutionId')||0,
                    pageNumber  : self.currentPage,  
                    pageSize    : self.itemsPerPage,  
                };
            $http
            ({
                url    : $scope.zsUrl+'digitalhome-boss/admin/institutions/getSublevelInfo',
                method : 'POST',
                data   : treeReqVo,

            }).success(function(res) {

                if(res.result_code != '0000') { 
                    $scope.isNoData = false;
                    return false;
                }
                    
                // 表格数据
                $scope.tabVal = res.result;
                // 遍历每条数据对应的ID
                angular.forEach(res.result, function(obj, i) {
                    $scope.dataID[i] = obj.institutionId;
                });
                // 总共有多少条数据
                self.totalItems = res.length;

            }).error(function(err) {
                $scope.isNoData = false;
            });

        }
    };

    // reload table
    $scope.reloadPagination = function() {
        $scope.paginationConf.onChange();
    };

    // newlyAdded get function name
    $scope.newlyAdded = function() { 
        superior();
    };

    // newlyAdded submit
    $scope.submitNewlyAdded = function() { 

        var selectedDate = new Date($scope.newlyAdded_validDate),
            year  = selectedDate.getFullYear(),
            month = selectedDate.getMonth()+1,
            date  = selectedDate.getDate();

        month<10?month=('0'+month):month=month;
        date<10?date=('0'+date):date=date;

        var submitDate = year +'-'+ month +'-'+ date;

        var newlyAddedData = {
            parentId                : cache.get('institutionId'),
            institutionId           : '',

            institutionName         : $scope.newlyAdded_institutionName||'',
            institutionDisplayName  : $scope.newlyAdded_institutionDisplayName||'',
            nature                  : $scope.newlyAdded_nature||'',
            contactName             : $scope.newlyAdded_contactName||'',
            industry                : $scope.newlyAdded_industry||'',
            institutionType         : $scope.newlyAdded_institutionType,
            enabled                 : $scope.newlyAdded_enabled,

            validDate               : submitDate,
            phone                   : $scope.newlyAdded_phone||'',
            postcode                : $scope.newlyAdded_postcode||'',
            province                : $scope.newlyAdded_province||'',
            city                    : $scope.newlyAdded_city||'',
            address                 : $scope.newlyAdded_address||'',

            description             : $scope.newlyAdded_description||'',

            institutionOrder        : '',
            createUserId            : '',
        }

        $http
        ({
            url         : $scope.zsUrl+'digitalhome-boss/admin/institutions/add',
            method      : 'POST',
            data        : newlyAddedData,

        }).success(function(res) {

            if( res.result_code != '0000' ) {
                promptCache.errorPrompt(res.message);
                return false;
            }

            promptCache.successPrompt(res.message);
            reloadTable();
            
        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });
    };

    // details
    $scope.details = function(i) { 

        superior();

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/admin/institutions/getInstitutionsInfo/'+$scope.dataID[i],
            method  : 'GET',

        }).success(function(res) {

            if( res.result_code != '0000' ) {
                return false;
            }

            $scope.details_institutionName          = res.result.institutionName;
            $scope.details_institutionDisplayName   = res.result.institutionDisplayName;
            $scope.details_nature                   = res.result.nature;
            $scope.details_contactName              = res.result.contactName;
            $scope.details_industry                 = res.result.industry;
            $scope.details_institutionType          = res.result.institutionType;
            $scope.details_enabled                  = res.result.enabled;

            $scope.details_validDate                = res.result.validDate;
            $scope.details_phone                    = res.result.phone;
            $scope.details_postcode                 = res.result.postcode;
            $scope.details_province                 = res.result.province;
            $scope.details_city                     = res.result.city;
            $scope.details_address                  = res.result.address;

            $scope.details_description              = res.result.description;

        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });         
    };

    // edit: show data
    $scope.edit = function(i) {

        superior();

        $scope.index = i;

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/admin/institutions/getInstitutionsInfo/'+$scope.dataID[i],
            method  : 'GET',

        }).success(function(res) {

            if( res.result_code != '0000' ) {
                return false;
            }

            $scope.edit_parentId                = res.result.parentId;

            $scope.edit_institutionName         = res.result.institutionName;
            $scope.edit_institutionDisplayName  = res.result.institutionDisplayName;
            $scope.edit_nature                  = res.result.nature;
            $scope.edit_contactName             = res.result.contactName;
            $scope.edit_industry                = res.result.industry;
            $scope.edit_institutionType         = res.result.institutionType;
            $scope.edit_enabled                 = res.result.enabled;

            $scope.edit_validDate               = new Date(res.result.validDate);
            $scope.edit_phone                   = res.result.phone;
            $scope.edit_postcode                = res.result.postcode;
            $scope.edit_province                = res.result.province;
            $scope.edit_city                    = res.result.city;
            $scope.edit_address                 = res.result.address;

            $scope.edit_description             = res.result.description;

            $scope.edit_lastUpdatedUserId       = res.result.lastUpdatedUserId;

            // institution type select
            $scope.EditInstitutionTypeSelect = 
            [
                { 'id': 0, 'name': '客户机构' },
                { 'id': 1, 'name': '代理商' },
                { 'id': 2, 'name': '应用提供商' },
                { 'id': 3, 'name': '供应商' },
            ];

            // institution status select
            $scope.EditInstitutionStatusSelect =
            [
                { 'id': 0, 'name': '禁用' },
                { 'id': 1, 'name': '启用' },
            ];

        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });
    };

    // edit: submit data
    $scope.submitEdit = function() {

        var selectedDate = new Date($scope.edit_validDate),
            submitDate = selectedDate.getFullYear() +'-'+ (selectedDate.getMonth()+1) +'-'+ selectedDate.getDate();

        var editData = {
            parentId                : $scope.edit_parentId||'',
            institutionId           : $scope.dataID[$scope.index]||'',

            institutionName         : $scope.edit_institutionName||'',
            institutionDisplayName  : $scope.edit_institutionDisplayName||'',
            nature                  : $scope.edit_nature||'',
            contactName             : $scope.edit_contactName||'',
            industry                : $scope.edit_industry,
            institutionType         : $scope.edit_institutionType,
            enabled                 : $scope.edit_enabled,

            validDate               : submitDate||'',
            phone                   : $scope.edit_phone||'',
            postcode                : $scope.edit_postcode||'',
            province                : $scope.edit_province||'',
            city                    : $scope.edit_city||'',
            address                 : $scope.edit_address||'',

            description             : $scope.edit_description||'',

            lastUpdatedUserId       : $scope.edit_lastUpdatedUserId||'',
        }

        $http
        ({
            url     : $scope.zsUrl+'digitalhome-boss/admin/institutions/modify',
            method  : 'POST',
            data    : editData,

        }).success(function(res) { console.log(res);

            if( res.result_code != '0000' ) {
                promptCache.errorPrompt(res.message);
                return false;
            }

            promptCache.successPrompt(res.message);
            reloadTable();

        }).error(function(err) {
            promptCache.errorPrompt('请求失败！');
            return false;
        });
    };

    // delete enable disabled
    $scope.getDataID = function() { 
        // data length
        var len = $scope.dataID.length;
        // param id
        var whichId = 'institutionId';
        // param
        var deleteUrl = 'admin/institutions/deleteInfo';
        // enable disabled
        var isEnableUrl = 'admin/institutions/modifyStatus';

        // multiple selections 
        $scope.selectAll= function (bool, obj) {
            selectCache.selectAll(bool, $scope.dataID);
        };

        //  Single or multiple selections 
        $scope.select= function (selectObj, bool) {   
            var selectId = selectObj.institutionId;        
            selectCache.select(selectId, bool, len);    
        }; 

        // check
        $scope.check= function () {
            selectCache.check();
        };

        // delete
        $scope.delete= function () { 
            selectCache.delete(whichId, deleteUrl);
            reloadTable();
        };

        // enable
        $scope.enable= function () { 
            selectCache.isEnable(whichId, isEnableUrl, 1);
            reloadTable();
        };

        // disabled
        $scope.disabled= function () { 
            selectCache.isEnable(whichId, isEnableUrl, 0);
            reloadTable();
        };
    };

    // superior
    function superior() {
        if( cache.get('institutionName') ) {
            $scope.institutionName = cache.get('institutionName');
        }else {
            $scope.institutionName = '最上级';
        }
    };
    // reload table
    function reloadTable() {
        $timeout(function() {
            $scope.paginationConf.onChange();
            $scope.master = false;
        },1500);
    };
}])
.directive('institutionNewlyadded', function() {
	return {
		restrict	: 'E',
		templateUrl : 'user/institution/newly_added.html',
		replace		: true,	
	}
})
.directive('institutionDelete', function() {
	return {
		restrict 	: 'E',
		templateUrl : 'user/institution/delete.html',
		replace		: true,	
	}
})
.directive('institutionDetails', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/institution/details.html',
		replace		: true,	
	}
})
.directive('institutionEdit', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/institution/edit.html',
		replace		: true,	
	}
})
.directive('institutionTable', function() {
	return {
		restrict	: 'E',
		templateUrl	: 'user/institution/table.html',
		replace		: true,	
	}
});
});